import { VxeUI } from 'vxe-pc-ui';
import { ElCascader } from 'element-plus';
import { getNestedPropertyValue } from './utils';

/**
 * 获取属性值的通用函数
 * @param {string} attrName - 属性名
 * @param {*} defaultValue - 默认值
 * @param {Object} sources - 属性来源对象数组
 * @returns {*} 属性值
 */
const getAttributeValue = (attrName, defaultValue, ...sources) => {
  for (const source of sources) {
    if (source && source[attrName] !== undefined) {
      return source[attrName];
    }
  }
  return defaultValue;
};

/**
 * 格式化级联选择器显示值的函数
 * @param {*} value - 原始值
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} props - 属性对象
 * @param {Object} attrs - 特性对象
 * @returns {string} 格式化后的显示值
 */
const formatCascaderValue = (value, renderOpts, props = {}, attrs = {}) => {
  if (
    value === null ||
    value === undefined ||
    value === '' ||
    (Array.isArray(value) && value.length === 0)
  ) {
    return '-';
  }

  // 获取格式化配置
  const formatter = getAttributeValue(
    'formatter',
    null,
    props,
    attrs,
    renderOpts,
  );
  const separator = getAttributeValue(
    'separator',
    ' / ',
    props,
    attrs,
    renderOpts,
  );
  const showAllLevels = getAttributeValue(
    'showAllLevels',
    true,
    props,
    attrs,
    renderOpts,
  );
  const options = getAttributeValue('options', [], props, attrs, renderOpts);

  let displayValue = '';

  // 自定义格式化函数优先
  if (formatter && typeof formatter === 'function') {
    displayValue = formatter(value, options);
  } else if (Array.isArray(value)) {
    // 如果有选项数据，尝试获取标签文本
    if (options && options.length > 0) {
      const labels = getCascaderLabels(value, options);
      if (labels.length > 0) {
        displayValue = showAllLevels
          ? labels.join(separator)
          : labels[labels.length - 1];
      } else {
        displayValue = showAllLevels
          ? value.join(separator)
          : value[value.length - 1];
      }
    } else {
      // 没有选项数据时直接显示值
      displayValue = showAllLevels
        ? value.join(separator)
        : value[value.length - 1];
    }
  } else {
    displayValue = String(value);
  }

  return displayValue || '-';
};

/**
 * 根据值路径获取对应的标签文本
 * @param {Array} valuePath - 值路径数组
 * @param {Array} options - 选项数据
 * @param {string} valueKey - 值字段名
 * @param {string} labelKey - 标签字段名
 * @param {string} childrenKey - 子节点字段名
 * @returns {Array} 标签文本数组
 */
const getCascaderLabels = (
  valuePath,
  options,
  valueKey = 'value',
  labelKey = 'label',
  childrenKey = 'children',
) => {
  const labels = [];
  let currentOptions = options;

  for (let i = 0; i < valuePath.length; i++) {
    const currentValue = valuePath[i];
    const option = currentOptions.find((opt) => opt[valueKey] === currentValue);

    if (option) {
      labels.push(option[labelKey] || option[valueKey]);
      currentOptions = option[childrenKey] || [];
    } else {
      labels.push(currentValue);
      break;
    }
  }

  return labels;
};

/**
 * 渲染级联选择器显示模式的通用函数
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderCascaderDisplay = (renderOpts, params) => {
  // 确定有效的数据和列上下文
  const effectiveData = params?.row || renderOpts.row || renderOpts.data || {};
  const effectiveColumn = params?.column || renderOpts.column || {};

  // 获取字段名
  const field =
    effectiveColumn.field || effectiveColumn.property || params?.field;

  if (!field) {
    console.warn('ElCascaderRender: Missing field identifier in display mode');
    return <span>-</span>;
  }

  // 获取当前值
  const value = getNestedPropertyValue(effectiveData, field);

  // 获取配置信息
  const props = renderOpts.props || {};
  const attrs = renderOpts.attrs || {};

  // 格式化显示值
  const displayValue = formatCascaderValue(value, renderOpts, props, attrs);

  // 获取样式配置
  const displayStyle = getAttributeValue(
    'displayStyle',
    {},
    props,
    attrs,
    renderOpts,
  );
  const className = getAttributeValue(
    'displayClass',
    '',
    props,
    attrs,
    renderOpts,
  );

  // 返回显示元素
  return (
    <span
      class={className}
      style={{
        padding: '4px 8px',
        minHeight: '20px',
        display: 'inline-block',
        ...displayStyle,
      }}
    >
      {displayValue}
    </span>
  );
};

/**
 * 通用渲染逻辑函数（用于编辑模式）
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderElCascader = (renderOpts, params) => {
  // 确定有效的数据和项上下文
  const effectiveData = params?.row || params?.data || renderOpts.data || {};
  const effectiveItem = params?.item || renderOpts.item || {};
  const effectiveColumn = params?.column || {};

  // 确定字段名
  const field =
    params?.field ||
    effectiveColumn.field ||
    effectiveItem.field ||
    renderOpts.field;

  if (!field) {
    console.error('ElCascaderRender: Missing field identifier in edit mode');
    return null;
  }

  // 获取当前值，使用辅助函数支持多层属性访问
  const value = getNestedPropertyValue(effectiveData, field);

  // 从effectiveItem中获取配置信息
  const itemRender = effectiveItem.itemRender || {};
  const props = itemRender.props || renderOpts.props || {};
  const attrs = itemRender.attrs || renderOpts.attrs || {};
  const events = itemRender.events || renderOpts.events || {};

  const title = effectiveColumn.title || effectiveItem.title || '';

  // 事件处理器
  const updateValue = (val) => {
    // 更新数据
    if (params?.row) {
      params.row[field] = val;
    } else if (params?.data) {
      params.data[field] = val;
    } else if (renderOpts.data) {
      renderOpts.data[field] = val;
    }

    // 触发原始事件
    events.input?.(val, effectiveData, params || renderOpts);
  };

  const handleChange = (val) => {
    // 触发change事件
    events.change?.(val, effectiveData, params || renderOpts);
  };

  const handleFocus = (event) => {
    // 触发focus事件
    events.focus?.(event, effectiveData, params || renderOpts);
  };

  const handleBlur = (event) => {
    // 触发blur事件
    events.blur?.(event, effectiveData, params || renderOpts);
  };

  const handleVisibleChange = (visible) => {
    // 触发visible-change事件
    events.visibleChange?.(visible, effectiveData, params || renderOpts);
  };

  const handleExpandChange = (value) => {
    // 触发expand-change事件
    events.expandChange?.(value, effectiveData, params || renderOpts);
  };

  const handleRemoveTag = (value) => {
    // 触发remove-tag事件
    events.removeTag?.(value, effectiveData, params || renderOpts);
  };

  // 构建级联选择器属性
  const cascaderProps = {
    modelValue: value,
    'onUpdate:modelValue': updateValue,
    onChange: handleChange,
    onFocus: handleFocus,
    onBlur: handleBlur,
    onVisibleChange: handleVisibleChange,
    onExpandChange: handleExpandChange,
    onRemoveTag: handleRemoveTag,

    // 基础属性
    options: getAttributeValue(
      'options',
      [],
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    props: getAttributeValue(
      'cascaderProps',
      {},
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    size: getAttributeValue(
      'size',
      undefined,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    placeholder: getAttributeValue(
      'placeholder',
      `请选择${title}`,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    disabled: getAttributeValue(
      'disabled',
      renderOpts.disabled || false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 显示配置
    showAllLevels: getAttributeValue(
      'showAllLevels',
      true,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    collapseTags: getAttributeValue(
      'collapseTags',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    collapseTagsTooltip: getAttributeValue(
      'collapseTagsTooltip',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    separator: getAttributeValue(
      'separator',
      ' / ',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 功能配置
    clearable: getAttributeValue(
      'clearable',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    filterable: getAttributeValue(
      'filterable',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    filterMethod: getAttributeValue(
      'filterMethod',
      null,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 弹出框配置
    popperClass: getAttributeValue(
      'popperClass',
      '',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    teleported: getAttributeValue(
      'teleported',
      true,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 标签相关
    tagType: getAttributeValue(
      'tagType',
      'info',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    maxCollapseTags: getAttributeValue(
      'maxCollapseTags',
      1,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 样式属性
    style: getAttributeValue('style', {}, props, attrs, itemRender, renderOpts),
    class: getAttributeValue('class', '', props, attrs, itemRender, renderOpts),

    // 验证相关
    validateEvent: getAttributeValue(
      'validateEvent',
      true,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
  };

  // 过滤掉值为null或undefined的属性
  const filteredProps = Object.fromEntries(
    Object.entries(cascaderProps).filter(
      ([key, value]) => value !== null && value !== undefined,
    ),
  );

  // 返回ElCascader组件
  return <ElCascader {...filteredProps} />;
};

// 注册支持多种上下文的渲染器
VxeUI.renderer.add('RaElCascaderRender', {
  // 表格单元格编辑模式
  renderTableEdit(renderOpts, params) {
    return renderElCascader(renderOpts, params);
  },

  // 表格单元格显示模式
  renderTableCell(renderOpts, params) {
    return renderCascaderDisplay(renderOpts, params);
  },

  // 表单项目渲染
  renderItemContent(renderOpts, params) {
    return renderElCascader(renderOpts, params);
  },

  // 默认显示模式（与renderTableCell相同）
  renderDefault(renderOpts, params) {
    return renderCascaderDisplay(renderOpts, params);
  },
});

export default 'RaElCascaderRender';
